﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GCELibrary.Current;
using ZF.BLL;
using ZF.Model;
using Gateway;
namespace ZF.WS.Person.space
{
    public partial class deposit : BLL.Page.GMPage
    {
        [PageArgument(Key = "f",  DefaultValue=null)]
        public string Flag { get; set; }
        [PageArgument(Key = "q", DefaultValue = 0)]
        public int Quantity { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "No-Cache");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (Flag!=null && Flag.EqIgnoreCase("buy") && Quantity > 0)
            {
                Buy(Quantity);
            }


        }
        protected void Buy(int quantity)
        {
       
            bool success = false;
            US_IntegralOrder order = null;
            using (var ts = new System.Transactions.TransactionScope())
            {
                using (var dc = SiteInfo.CreateDBDataContext())
                {
                      order = new ZF.Model.US_IntegralOrder()
                    {
                        AddTime = DateTime.Now,
                        MemberId = this.CurrentUser.MemberId,
                        PayStatus = (int)PayStatus.NEW_PAY,
                        Quantity = quantity,
                        Price = (decimal)quantity / 10,
                        No=Guid.NewGuid().ToString(),
                    };
                    try
                    {
                        dc.US_IntegralOrder.InsertOnSubmit(order);
                        dc.SubmitChanges();
                        order.No = "i" + (order.IntegralOrderId + 10000).ToString();
                        dc.SubmitChanges();
                        ts.Complete();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        throw WarnFactory.CreateWarn(ex);
                    }
                }
            }
            if (success)
            {
                PostToAlipay(order);
 
            }
        }



        protected void PostToAlipay(Model.US_IntegralOrder order)
        {
            var alipayset = SiteInfo.SystemConfig.AlipaySet;


            //业务参数赋值；
            string gateway = alipayset.Gateway;	//支付接口
            string service = alipayset.Service;                       //服务名称，这个是识别是何接口实现何功能的标识，请勿修改

            string seller_email = alipayset.SellerEmail;                     //商家签约时的支付宝帐号，即收款的支付宝帐号
            string sign_type = "MD5";                                           //加密类型,签名方式“不用改”
            string key = alipayset.Key;                    //安全校验码，与partner是一组，获取方式是：用签约时支付宝帐号登陆支付宝网站www.alipay.com，在商家服务我的商家里即可查到。
            string partner = alipayset.Partner;                                //商户ID，合作身份者ID，合作伙伴ID
            string _input_charset = "utf-8";                                    //编码类型，完全根据客户自身的项目的编码格式而定，千万不要填错。否则极其容易造成MD5加密错误。

            string show_url = Request.Url.ToString();                       //展示地址，即在支付页面时，商品名称旁边的“详情”的链接地址。

            string out_trade_no = order.No;                       //客户自己的订单号，订单号必须在自身订单系统中保持唯一性
            string subject =   string.Format("{0}会员积分", SiteInfo.SystemConfig.SiteName);                          //商品名称，也可称为订单名称，该接口并不是单一的只能买一样东西，可把一次支付当作一次下订单
            string body =  string.Format("在线购买{0}个积分,订单号：{1}",order.Quantity, order.No); ;
            //商品描述，即备注
            string total_fee = order.Price.ToString();                        //商品价格，也可称为订单的总金额



            //服务器通知url（Alipay_Notify.aspx文件所在路经），必须是完整的路径地址
            string notify_url = SiteInfo.SystemConfig.Domain + "/Person/space/Alipay_Notify.aspx";
            //服务器返回url（Alipay_Return.aspx文件所在路经），必须是完整的路径地址
            string return_url = SiteInfo.SystemConfig.Domain + "/Person/space/Alipay_Return.aspx";

            //构造数组；
            //以下数组即是参与加密的参数，若参数的值不允许为空，若该参数为空，则不要成为该数组的元素
            string[] para ={
                    "service="+service,
                    "partner=" + partner,
                    "seller_email=" + seller_email,
                    "out_trade_no=" + out_trade_no,
                    "subject=" + subject,
                    "body=" + body,
                    "total_fee=" + total_fee, 
                    "show_url=" + show_url,
                    "payment_type=1",
                    "notify_url=" + notify_url,
                    "return_url=" + return_url,
                    "_input_charset="+_input_charset
                    };





            ////支付URL生成Get方式
            //string aliay_url = AliPay.CreatUrl(gateway, para, _input_charset, sign_type, key);
            ////以下是GET方式传递参数
            //Response.Redirect(aliay_url);




            //支付URL生成Post方式
            string aliay_url = AliPay.CreatUrl(para, _input_charset, sign_type, key);
            //以下是POST方式传递参数
            Response.Write("<form name='alipaysubmit' method='post' action='https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8'>");
            Response.Write("<input type='hidden' name='service' value=" + service + ">");
            Response.Write("<input type='hidden' name='partner' value=" + partner + ">");
            Response.Write("<input type='hidden' name='seller_email' value=" + seller_email + ">");
            Response.Write("<input type='hidden' name='out_trade_no' value=" + out_trade_no + ">");
            Response.Write("<input type='hidden' name='subject' value=" + subject + ">");
            Response.Write("<input type='hidden' name='body' value=" + body + ">");
            Response.Write("<input type='hidden' name='total_fee' value=" + total_fee + ">");
            Response.Write("<input type='hidden' name='show_url' value=" + show_url + ">");
            Response.Write("<input type='hidden' name='return_url' value=" + return_url + ">");
            Response.Write("<input type='hidden' name='notify_url' value=" + notify_url + ">");
            Response.Write("<input type='hidden' name='payment_type' value=1>");
            Response.Write("<input type='hidden' name='sign' value=" + aliay_url + ">");
            Response.Write("<input type='hidden' name='sign_type' value=" + sign_type + ">");
            Response.Write("</form>");
            Response.Write("<script>");
            Response.Write("document.alipaysubmit.submit()");
            Response.Write("</script>");
            Response.End();
        }
    }
}
